package core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Klasa łącząca się z bazą danych
 * @author Marcin
 */

public class SqlConnection {
    private static final Integer timeOut = 10;
    private Connection conn = null;

    private SqlConnection() {
    }

    private static class SqlConnectionHolder {
        private static final SqlConnection INSTANCE = new SqlConnection();
    }

    /**
     * Zwraca singleton klasy
     *
     * @return obiekt klasy SqlConnection
     */
    public static SqlConnection getInstance() {
        return SqlConnectionHolder.INSTANCE;
    }
    /**
     * Zwraca obiekt klasy Connection potrzebny do wykonania zapytan SQL
     *
     * @return obiekt klasy Connection
     */
    public Connection getSqlConnection() throws SQLException{
        try {
            if (conn == null || !conn.isValid(timeOut)) {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
                conn = DriverManager.getConnection(
                        "jdbc:sqlserver://localhost:1433;databaseName=BazaPrzychodni;integratedSecurity=true;");
                System.out.println("Połączenie z bd:OK!");
            }
            return conn;
        } catch (ClassNotFoundException ex) {            
            ErrorLogger.getInstance().log("Błąd sterownika jdbc", false, null);
        }
        return null;
    }
    public static int getRowCount(ResultSet set) throws SQLException  
    {  
       int rowCount;  
       int currentRow = set.getRow();            // Get current row  
       if(set!=null && set.last()) rowCount = set.getRow(); else rowCount = 0; // Determine number of rows  
       if (currentRow == 0) {
            set.beforeFirst();
        }                     // We want next() to go to first row  
       else {
            set.absolute(currentRow);
        }              // Restore it  
       return rowCount;  
    }
}
